package com.yichuang.security.jwt.main.service;

import com.yichuang.security.common.OAuth2Client;
import com.yichuang.security.common.utils.BASE64Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * <p></p>
 *
 * @author tuonioooo
 * @site https://miliqkdoc.motopa.cn/
 * @date 2020/6/20 12:30
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OAuth2Service {

    private final RestTemplate restTemplate;

    @Value("${server.port}")
    private String port;

    /**
     * 获取token
     *
     * @param username
     * @param password
     * @return
     */
    public String getToken(String username, String password) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.set("grant_type", "password");//授权类型  密码模式
        params.set("username", username);
        params.set("password", password);
        return postForEntity(params);
    }

    /**
     * 刷新token
     *
     * @param username
     * @param password
     * @return
     */
    public String refreshToken(String username, String password, String refreshToken) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.set("grant_type", "refresh_token");//授权类型  刷新token模式
        params.set("username", username);
        params.set("password", password);
        params.set("refresh_token", refreshToken);
        return postForEntity(params);
    }

    private String postForEntity(MultiValueMap<String, String> params) {
        HttpHeaders headers = new HttpHeaders();
        //进行base64编码  将客户端id和客户端密码拼接，按“客户端id:客户端密码”
        byte[] encode = BASE64Utils.encodeBase64(OAuth2Client.CLIENT_ID + ":" + OAuth2Client.CLIENT_SECRET);
        headers.add("Authorization", "Basic " + new String(encode));
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(params, headers);
        String url = String.format(OAuth2Client.OAUTH_TOKEN_URL, OAuth2Client.IP, port);
        log.info("OAuth2 请求地址={}", url);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
        return responseEntity.getBody();
    }

}
